<?php

namespace App\Services;

use App\Models\UserAuthModel;
use App\Models\UserModel;
use Framework\BaseService;
use Framework\Hope;
use Framework\Jwt;
use Framework\ModelEncryptionTrait;
use GuzzleHttp\Client;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Ytake\LaravelAspect\Annotation\Transactional;

class RegisterService extends BaseService
{
    use ModelEncryptionTrait;

    private $jwt;

    public function __construct(Jwt $jwt)
    {
        $this->jwt = $jwt;
    }

    public function pre_register($phone)
    {

        $flg = UserModel::query()->where('phone', $this->encryptAttribute($phone))->exists();
        if ($flg) {
            $this->retError('手机号已存在');
        }
        return true;
    }


    public function pre_two_register($real_name, $idcard_num)
    {
        //身份认证
        $idcardArr = app(AuthService::class)->idcard($real_name, $idcard_num);
        $idcardInfo = json_decode($idcardArr['data'], true);
        if ($idcardInfo['status'] !== '01') {
            $this->retError('填写的身份信息有误');
        }

        return $idcardInfo;


    }

    /**
     * @Transactional()
     * @param $phone
     * @param $code
     * @param $password
     * @param $nickname
     * @param $real_name
     * @param $idcard_num
     * @return array
     * @throws \Throwable
     */
    public function register($phone, $code, $password, $nickname, $real_name, $idcard_num)
    {
        if (!Hope::validatePhone($phone)) {
            $this->retError('请输入正确的手机号');
        }

        //验证短信验证码
        app(SmsService::class)->checkSmsCode($phone, $code);
        //检查手机

        //二要素检验
        $this->pre_register($phone);
        if (Hope::isProduct()) {
            $idcard = $this->pre_two_register($real_name, $idcard_num);
        } else {
            $idcard = [
                'birthday' => "1998-8-8",
                'sex' => "男",
                'province' => "陕西省",
                'city' => "西安市",
                'area' => "陕西省西安市",
            ];
        }

        $sex = $idcard['sex'];
        $sex_int = $sex == '女' ? 1 : 0;

        $user = new UserModel();
        DB::beginTransaction();
        try {
            $user->nickname = $nickname;
            $user->sex = $sex_int;
            $user->birthday = $idcard['birthday'];
            $user->province = $idcard['province'];
            $user->city = $idcard['city'];
            $user->address = $idcard['area'];
            $user->phone = $phone;
            $user->password = Hash::make($password);;
            $user->true_name = $real_name;
            $user->is_auth = 1;
            $user->is_face_auth = 0;
            if (!$user->save()){
                DB::rollBack();
                $this->retError('注册失败');
            }

            $this->insertAuthentication($user->id, $real_name, $idcard_num);
            DB::commit();
            $jwt_str = $this->jwt->getToken((string)$user->id);

            return compact('jwt_str');
        }catch (\Exception $exception){
            DB::rollBack();
            $this->retError($exception->getMessage());
        }
        //增加七牛IM账户
        /* $qiniu = new QiNiuService();
         $qret = $qiniu->imRegister('im_dev'.$user->id);
         if($qret[0]['code']==200)
         {
             $user->update(['qiniu_uid'=>$qret[0]['data']['user_id']]);
         }*/
    }


    /**
     * * 身份认证入库.
     * @param $user_id
     * @param $realName
     * @param $idcardNum
     */
    public function insertAuthentication($user_id, $realName, $idcardNum)
    {


        $idcard_auth = UserAuthModel::query()
            ->where('idcard_num', $this->encryptAttribute($idcardNum))
            ->first();
        if ($idcard_auth) {

            $this->retError('此身份信息已经认证了');
        }

        $userAuth = new  UserAuthModel();
        $userAuth->user_id = $user_id;
        $userAuth->idcard_name = $realName;
        $userAuth->idcard_num = $idcardNum;
        $userAuth->card_name = "身份证";
        $userAuth->add_time = Carbon::now();
        $userAuth->pass_time = Carbon::now();
        $userAuth->save();
    }
}
